<template>
  <div class="app-container">
    <div v-show="!isLoading" class="article">
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="header">
            <h1 class="title">{{ article.title }}</h1>
            <div class="author">
              <div class="avatar">
                <el-tooltip content="点击关注作者" placement="right">
                  <img class="auth-logo" :src="getImageSrc(article.user.avatar)" @click="handleWatch(article.articleId)">
                </el-tooltip>
              </div>
              <div class="info">
                <span class="name">
                  <span>{{ article.user.userName }}</span>
                </span>
                <div props-data-classes="user-follow-button-header" data-author-follow-button="" />
                <div class="meta">
                  <span class="publish-time">
                    {{ article.createTime? getTime(article.createTime): '' }}
                  </span>
                  <span class="views-count">
                    阅读 {{ article.views }}
                  </span>
                  <span class="comments-count">
                    评论 {{ article.comments }}
                  </span>
                  <el-tooltip content="点击收藏文章" placement="top">
                    <span class="likes-count" @click="handleFavor(article.articleId)">
                      收藏 {{ article.favors }}
                    </span>
                  </el-tooltip>
                </div>
              </div>
              <div class="tags" title="标签">
                <el-tag v-for="(tag) in article.tagArr" :key="tag" size="mini" class="tag" type="success">{{ tag }}</el-tag>
              </div>
              <span class="clearfix" />
            </div>
          </div>
        </el-col>
        <el-col :span="24">
          <div class="content">
            <div v-if="article.thumbnail && article.channel !== '3' && article.channel !== '4'" class="img-container">
              <img :src="getImageSrc(article.thumbnail)" class="image">
            </div>
            <div id="video_play" width="100%" />
            <template v-if="article.channel !== '4'">
              <div v-if="article.editor !== 'markdown'" class="article-detail" v-html="article.content" />
              <div v-if="article.editor === 'markdown'" class="article-detail">
                <el-row :gutter="20">
                  <el-card style="margin-right: 300px">
                    <mavon-editor
                      ref="md"
                      v-model="article.content"
                      style="width: 100%"
                      :subfield="false"
                      default-open="preview"
                      :editable="false"
                      :toolbars-flag="false"
                      :short-cut="false"
                    />
                  </el-card>
                  <el-card class="box-card menu-box">
                    <div slot="header" class="clearfix">
                      <span>目录导航</span>
                    </div>
                    <menu-tree :menus="menus" child-label="child" />
                  </el-card>
                </el-row>
              </div>
            </template>
            <el-carousel
              ref="remarkCarusel"
              height="50px"
              :autoplay="false"
              :initial-index="article.current"
              indicator-position="none"
              arrow="click"
            >
              <el-carousel-item v-for="(group, index) in article.groups" :key="index" name="index">
                <h3 class="medium" @click="changeVideo(group.articleId)">{{ group.title }}</h3>
              </el-carousel-item>
            </el-carousel>
            <comment
              v-if="user.userId&&user.userId!==article.user.userId"
              :avatar="getImageSrc(article.user.avatar)"
              comment-width="90%"
              :comment-num="commentNum"
              :author-id="user.userId"
              :comment-list="commentList"
              @doSend="sendComment"
              @doChidSend="sendComment"
            />
            <arrow-up ref="arrow_up" />
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import Player from 'xgplayer'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import MenuTree from '@/components/MenuTree'
import Comment from '@/components/HblComment'
import ArrowUp from '@/components/ArrowUp'

export default {
  name: 'Info',
  components: { Comment, mavonEditor, MenuTree, ArrowUp },
  data() {
    return {
      article: {
        articleId: undefined,
        title: '',
        thumbnail: undefined,
        user: {
          avatar: '',
          userName: ''
        },
        channel: undefined,
        direction: undefined,
        tags: undefined,
        tagArr: [],
        content: '',
        current: 0,
        groups: [],
        views: 0,
        comments: 0,
        favors: 0,
        createTime: undefined,
        editor: undefined
      },
      menus: [],
      commentNum: 0,
      commentList: [],
      playerObj: null,
      isLoading: true,
      isMarked: false
    }
  },
  computed: {
    ...mapState({
      user: state => state.user.info
    })
  },
  watch: {
    $route: {
      handler: function(route) {
        this.article.articleId = route.query && route.query.articleId
      },
      immediate: true
    }
  },
  mounted() {
    this.init(this.article.articleId)
  },
  methods: {
    getTime: function(value) {
      return this.$api.diffDateBefore(value)
    },
    getImageSrc(thumbnail) {
      return this.$api.getImageSrc(thumbnail)
    },
    getVideoSrc(src) {
      return this.$api.getVideoSrc(src)
    },
    init(articleId) {
      this.$nextTick(() => {
        this.$http.get('/blog/query/article/' + articleId).then(response => {
          this.article = this.$api.objectUpdate(this.article, response.param)
          this.commentList = response.param.commentList
          if (this.article.tags && this.article.tags.length > 0) {
            this.article.tagArr = this.article.tags.split(',')
          }
          this.isLoading = false
          if (this.article.channel === '4') {
            let fitSize = 'auto'
            if (this.article.direction === 'horizontal') {
              fitSize = 'fixWidth'
            } else if (this.article.direction === 'vertical') {
              fitSize = 'fixHeight'
            }
            this.playerObj = new Player({
              id: 'video_play',
              url: this.getVideoSrc(this.article.content),
              fluid: true, // 流式布局
              fitVideoSize: fitSize, // 自适应视频内容宽高
              autoplay: false, // 自动播放
              loop: false, // 循环播放
              playbackRate: [0.5, 0.75, 1, 1.5, 2], // 倍速播放
              defaultPlaybackRate: 1, // 默认播放速度
              pip: false, // 画中画
              download: true, // 下载按钮
              screenShot: true, // 截图
              controls: true // 显示控制条
            })
          } else if (this.article.editor === 'markdown') {
            this.$nextTick(function() {
              // 删除插件目录
              let e = document.querySelector('.v-note-read-content')
              if (e) {
                e.parentNode.removeChild(e)
              }
              e = document.querySelector('.v-show-content-html')
              if (e) {
                e.parentNode.removeChild(e)
              }
              this.createMenus()
            })
          }

          if (this.article.groups.length > 0) {
            this.$refs.remarkCarusel.setActiveItem(this.article.current)
          }
          this.topFunction()
        }).catch(() => {})
      })
    },
    changeVideo(id) {
      this.playerObj.destroy()
      this.init(id)
    },
    // 生成目录
    createMenus() {
      let arr = []
      for (let i = 6; i > 0; i--) {
        const temp = []
        const e = document.querySelector('.v-show-content').querySelectorAll(`h${i}`)
        for (let j = 0; j < e.length; j++) {
          const child = this.fetchH(arr, e[j].offsetTop, (j + 1 === e.length) ? undefined : e[j + 1].offsetTop)
          temp.push({
            h: i,
            title: e[j].innerText,
            id: e[j].querySelector('a').id,
            offsetTop: e[j].offsetTop,
            child
          })
        }
        if (temp.length) {
          arr = temp
        }
      }
      this.menus = arr
    },
    fetchH(arr, left, right) {
      if (right) {
        return arr.filter(item => item.offsetTop > left && item.offsetTop < right)
      } else {
        return arr.filter(item => item.offsetTop > left)
      }
    },
    handleFavor(id) {
      this.$http.get('/blog/favor/' + id).then(response => {
        if (response.param === 1) {
          this.article.favors = parseInt(this.article.favors) + 1
          this.$message({
            type: 'success',
            message: '成功收藏文章'
          })
        } else if (response.param === -1) {
          this.article.favors = parseInt(this.article.favors) - 1
        }
      }).catch(e => {})
    },
    handleWatch(id) {
      this.$http.get('/blog/watcher/' + id).then(response => {
        if (response.param === 1) {
          this.$message({
            type: 'success',
            message: '成功关注作者'
          })
        }
      }).catch(e => {})
    },
    topFunction() {
      this.$refs.arrow_up.topFunction()
    },
    sendComment(content, targetUser, parentId) {
      this.$http.post('/blog/saveComment', {
        articleId: this.article.articleId,
        targetUser: targetUser,
        parentId: parentId,
        content: content
      }).then(response => {
        this.$message({
          type: 'success',
          message: response.msg
        })
        this.article.comments++
        this.$http.get('/blog/query/article/' + this.article.articleId).then(response => {
          this.commentList = response.param.commentList
        }).catch(() => {})
      })
    },
    close() {
      this.playerObj.destroy()
      this.isLoading = true
      this.article = {
        articleId: undefined,
        title: '',
        user: {
          avatar: '',
          userName: ''
        },
        channel: undefined,
        tags: undefined,
        tagArr: [],
        content: '',
        groups: [],
        views: 0,
        comments: 0,
        favors: 0,
        createTime: undefined,
        editor: undefined
      }
    }
  }
}
</script>

<style>
  @import '~@/styles/prism.css';
</style>

<style lang="less" scoped>
.article {
  padding-left: 35px;

  .header {
    .title {
      margin: 20px 0 0;
      text-align: center;
      font-size: 34px;
      font-weight: bold;
    }
    .author {
      position: relative;
      margin: 30px 0 40px;
      padding-left: 50px;
      .avatar {
        position: absolute;
        left: 0;
        top: 0;
        width: 48px;
        height: 48px;
        vertical-align: middle;
        display: inline-block;
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }
      .info {
        float: left;
        vertical-align: middle;
        // display: inline-block;
        margin-left: 8px;
        a {
          color: #333;
        }
      }
      .name {
        margin-right: 3px;
        font-size: 16px;
        vertical-align: middle;
      }
      .meta {
        margin-top: 5px;
        font-size: 12px;
        color: #969696;
        span {
          padding-right: 5px;
        }
      }
      .tags {
        float: right;
        padding-top: 15px;
        .tag {
          margin-left: 5px;
          border-right: 2px solid #eee;
        }
      }
    }
  }
}

.v-note-wrapper {
  z-index: 0 !important;
}

.menu-box {
  position: fixed;
  top: 260px;
  right: 0px;
  z-index: 1000;
}

.content {
  position: relative;
  .article-detail {
      padding: 0 10px;
  }
}

.img-container {
  display: flex;
  width: 100%;
  justify-content: center;

  .image {
    height: auto;
    max-width: 100%;
    max-height: 260px;
    object-fit: fill;
  }
}
</style>
